part of shop;
// import 'package:flutter/services.dart';
// import 'package:image_picker/image_picker.dart';

class NewPostPage extends StatefulWidget {
  const NewPostPage({Key? key}) : super(key: key);


  @override
  State<NewPostPage> createState() => _NewPostPageState();
}

class _NewPostPageState extends State<NewPostPage> {
  /// 商品名
  late TextEditingController _controllerOfName,_controllerOfPrice,_controllerOfIntroduce;

  /// 商品价格
  double price = 0.0;

  /// 是否使用qq
  bool qq = true;

  /// 是否使用微信
  bool wx = true;

  /// 是否使用手机号
  bool tel = true;

  /// 图片
  late List<Widget> imageList = [
    Card(
        color: Color.fromRGBO(241, 241, 241, 1),
        child: SizedBox(
          height: 100,
          width: 100,
          child: IconButton(
            alignment: Alignment.center,
            color: Colors.grey,
            icon: Icon(
              Icons.add_photo_alternate_outlined,
            ),
            onPressed: () async {
              ImagePicker imagePicker = ImagePicker();
              XFile? imgFile =
              await imagePicker.pickImage(source: ImageSource.gallery);
              // for (XFile f in imgFile) {
              // fileList.add(f);
              // imageList.insert(
              //     imageList.length - 1,
              //     Image.memory(
              //       await f.readAsBytes(),
              //       fit: BoxFit.cover,
              //       height: 100,
              //       width: 100,
              //     )
              // );
              if (imgFile != null) {
                fileList.add(imgFile);
                var data = await imgFile.readAsBytes();
                setState(() {
                  imageList.add(Image.memory(
                    data,
                    fit: BoxFit.cover,
                    height: 100,
                    width: 100,
                  ));
                });
              }
            },
          ),
        ))
  ];
  List<XFile> fileList = [];

  @override
  void initState() {
    super.initState();
    _controllerOfName = TextEditingController();
    _controllerOfPrice = TextEditingController();
    _controllerOfIntroduce = TextEditingController();
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromRGBO(240, 240, 240, 1.0),
      appBar: AppBar(
        title: const Text(
          "发布商品",
          style: TextStyle(color: Colors.black87),
        ),
        elevation: 0.2,
        backgroundColor: Colors.white,
        actions: [
          TextButton(onPressed: (){
            _clear ()async {
              qq=true;
              wx=true;
              tel=true;
              _controllerOfPrice.text="";
            }
            AppTool().showCenterTipsAlter(context, _clear, "您确定要删除收藏得商品吗", "温馨提示");
          },
            child: Text("恢复"),),
          TextButton(
              onPressed: () {
                if(fileList.isEmpty){
                  showDialog(
                      builder: (BuildContext context) =>
                          ShowDefineAlertWidget(
                                  () {}, "发布失败", "您还未选择图片"),
                      context: context);
                }
                else{
                User._cache?.getLocalInfo().then((value) {
                  Map infomap = json.decode(value);
                  List<String> product_coverimg = [];
                  for(int i = 0;i < fileList.length ;i++){
                    String coverimguri = upload(fileList[i].path);
                    product_coverimg.add(coverimguri);
                  }
                  Map<String, dynamic> productmap = {
                    'product_id': 1,
                    'product_name': _controllerOfName.text,
                    "product_price": _controllerOfPrice.text,
                    'sell_status': 0,
                    'product_created_time': DateTime
                        .now()
                        .millisecondsSinceEpoch,
                    "product_intro": "",
                    "product_zone": "",
                    "seller_id":
                    json.decode(infomap["id"]),
                    "connection": {"wx": wx==true?0:1, "qq": qq==true?0:1, "tel": tel==true?0:1},
                    "product_coverimg": product_coverimg,
                  };
                  Product.updateProduct(productmap).then((value) {
                    if (value != 200) {
                      print("商品上传有误");
                    }
                  });
                });// Navigator.of(context).pop();
              }},
              child: Text(
                "发布",
                style: TextStyle(
                  fontSize: 20,
                ),
              ))
        ],
      ),
      body: ListView(
        padding: EdgeInsets.all(7),
        children: [
          Card(
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            elevation: 5,
            child: Padding(
              padding: EdgeInsets.fromLTRB(30, 25, 30, 30),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text("商品名"),
                  ),
                  Card(
                    color: Color.fromRGBO(241, 241, 241, 1),
                    child: TextFormField(
                      controller: _controllerOfName,
                      enableInteractiveSelection: true,
                      style: TextStyle(fontSize: 16),
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.fromLTRB(20, 5, 10, 5),
                          suffix: Text(
                              (12 - _controllerOfName.text.length).toString())),

                      inputFormatters: [
                        // 限制长度
                        LengthLimitingTextInputFormatter(12),
                      ],
                      // maxLength: 20,
                      onChanged: (value) {
                        setState(() {});
                      },
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "价格",
                      textAlign: TextAlign.left,
                    ),
                  ),
                  Card(
                    color: Color.fromRGBO(241, 241, 241, 1),
                    child: TextFormField(
                      controller: _controllerOfPrice,
                      decoration: InputDecoration(
                        prefix: Text(
                          "￥",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.fromLTRB(20, 5, 10, 5),
                      ),
                      keyboardType: TextInputType.numberWithOptions(),
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(RegExp(r"[\d.]"))
                      ],
                      onChanged: (value) {
                        double? res = double.tryParse(value);
                        if (res != null) {
                          setState(() {
                            price = res;
                          });
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Card(
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            elevation: 5,
            child: Padding(
              padding: EdgeInsets.fromLTRB(30, 20, 30, 24),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text("商品介绍"),
                  ),
                  Card(
                    color: Color.fromRGBO(241, 241, 241, 1),
                    child: TextFormField(
                      controller: _controllerOfIntroduce,
                      enableInteractiveSelection: true,
                      maxLines: 5,
                      maxLength: 150,
                      style: TextStyle(fontSize: 15),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.fromLTRB(12, 5, 12, 5),
                      ),
                      onChanged: (value) {},
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Card(
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            elevation: 5,
            child: Padding(
              padding: EdgeInsets.fromLTRB(30, 20, 30, 24),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text("联系方式"),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text("QQ"),
                      Checkbox(
                          value: qq,
                          onChanged: (value) {
                            qq = value!;
                            setState(() {});
                          }),
                      SizedBox(
                        width: 15,
                      ),
                      Text("微信"),
                      Checkbox(
                          value: wx,
                          onChanged: (value) {
                            wx = value!;
                            setState(() {});
                          }),
                      SizedBox(
                        width: 15,
                      ),
                      Text("手机"),
                      Checkbox(
                          value: tel,
                          onChanged: (value) {
                            tel = value!;
                            setState(() {});
                          }),
                    ],
                  )
                ],
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Card(
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            elevation: 5,
            child: Padding(
              padding: EdgeInsets.fromLTRB(30, 20, 30, 24),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text("图片"),
                  ),
                  GridView.count(
                    crossAxisCount: 3,
                    shrinkWrap: true,
                    crossAxisSpacing: 5,
                    mainAxisSpacing: 10,
                    cacheExtent: 0,
                    children: imageList,
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
